package naga.x.platform2.channel.sina;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import naga.x.platform2.app.Channel;
import naga.x.platform2.app.model.Recharge;
import naga.x.platform2.app.model.RechargeTemplate;
import naga.x.platform2.app.support.RechargeSupport;
import naga.x.platform2.channel.sina.support.SinaApi;
import naga.x.platform2.channel.sina.support.SinaConfig;
import naga.x.platform2.support.RequestPath;
import naga.x.platform2.utils.CommonUtils;
import naga.x.platform2.utils.HttpUtils;
import naga.x.platform2.utils.IOUtils;
import naga.x.platform2.utils.NumberUtils;
import naga.x.platform2.utils.StringUtils;

/**
 * @see <a href=
 *      "http://git.oschina.net/sinagamesdk/sinagamesdk-h5/blob/master/%E6%96%B0%E6%B5%AA%E6%B8%B8%E6%88%8FH5%E6%8E%A5%E5%85%A5%E6%96%87%E6%A1%A3.md">
 *      新浪游戏H5</a>
 * @author yang.li
 *
 */
@Controller
public class SinaController {

	@Autowired
	private SinaConfig config;
	@Autowired
	private RechargeSupport support;
	
	private static Channel channel = Channel.SINA;
	
	private static final Logger LOG = LoggerFactory.getLogger(SinaController.class);
	
	@RequestMapping(path = RequestPath.SINA_USER_CHECK, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public Object valiUser(String uid, String token, String device) {
		Map<String, String> params = new TreeMap<>();
		params.put("suid", uid);
		params.put("appkey", config.getAppKey());
		params.put("deviceid", StringUtils.isEmpty(device) ? "H5" : device);
		params.put("token", token);
		params.put("signature", SinaApi.makeSign(params, config.getSignKey()));

		String res = HttpUtils.post(config.getValidateUserUrl(), params);
		JSONObject json = JSON.parseObject(res);
		Object suid = json.remove("suid");
		if (suid != null) {
			json.put("uid", suid);
		}
		return json;
	}
	
	@RequestMapping(RequestPath.SINA_ORDER)
	public String getOrder(String uid, String token, Integer sid, Integer product, HttpServletRequest request, HttpServletResponse response) {
		RechargeTemplate template = support.getTemplate(product);
		response.setHeader("Access-Control-Allow-Origin", "*");
		if (template == null) {
			return UrlBasedViewResolver.REDIRECT_URL_PREFIX + config.getClientUrl();
		}
//		appkey	string	开放平台给应用分配的appkey	true
//		access_token	string	用户身份标识	true
//		amount	int	支付金额，单位 分	true
//		uid	string	用户id	true
//		subject	string	商品名称	true
//		desc	string	商品描述，将会显示在支付页面，不能为空	true
//		show_url	string	支付的前端回调，默认传入游戏的入口地址	true
//		pt	string	透传参数,在支付回调中，会原样返回	false
		if (uid.startsWith(channel.prefix)) {
			uid = uid.substring(channel.prefix.length());
		}
		
		Map<String, String> params = new LinkedHashMap<>();
		params.put("appkey", config.getAppKey());
		params.put("access_token", token);
		params.put("amount", String.valueOf(template.getPrice() * 100));
		params.put("uid", uid);
		params.put("subject", CommonUtils.encodeURL(template.getName(), IOUtils.UTF8));
		params.put("desc", CommonUtils.encodeURL(StringUtils.isEmpty(template.getDesc()) ? template.getName() : template.getDesc(), IOUtils.UTF8));
		params.put("show_url", CommonUtils.encodeURL(config.getClientUrl(), IOUtils.UTF8));
		params.put("pt", sid + ":" + product);
		params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
		String url = config.getPayUrl() + '?' + HttpUtils.wrapQueryString(params);
		
		return UrlBasedViewResolver.REDIRECT_URL_PREFIX + url;
	}
	
	@RequestMapping({ RequestPath.SINA_PAY_CALLBACK, RequestPath.SINA_PAY_CALLBACK1 })
	@ResponseBody
	public Object payback(String order_id, Integer amount, String order_uid, String source, Integer actual_amount, String pt, String signature) {
//		order_id	string	调用下单接口获取到的订单号	true
//		amount	int	支付金额，单位 分	true
//		order_uid	string	支付用户id	true
//		source	string	应用的appkey	true
//		actual_amount	int	实际支付金额，单位 分	true
//		pt	string	透传参数（该参数的有无决定于下单时有没有上传pt参数）	true
//		signature	string	用于参数校验的签名，生成办法参考2.3	true
		Map<String, String> map = new TreeMap<>();
		map.put("order_id", order_id);
		map.put("amount", String.valueOf(amount));
		map.put("order_uid", order_uid);
		map.put("source", source);
		map.put("actual_amount", String.valueOf(actual_amount));
		map.put("pt", pt);
		String sign = SinaApi.makeSignOfPay(map, config.getAppSec());
		boolean succ = false;
		if (sign.equals(signature)) {
			String[] strs = StringUtils.split(pt, ":");
			int serverId = strs != null && strs.length > 0 ? NumberUtils.parseInt(strs[0]) : 0;
			int product = strs != null && strs.length > 1 ? NumberUtils.parseInt(strs[1]) : 0;
			RechargeTemplate template = support.getTemplate(product);
			if (template != null && actual_amount >= template.getPrice() * 100) {
				Recharge recharge = new Recharge(channel.prefix + order_id, 0, serverId, actual_amount / 100, template.getStone(), product, channel.name);
				recharge.setChannelUid(channel.withPrefix(order_uid));
				succ = support.offer(recharge);
			}
		}
		LOG.info("[SINA PAY]UID[{}]ORDER[{}]AMOUNT[{}]AMOUNT1[{}]SOURCE[{}]PT[{}]SIGN[{}]SIGN2[{}]SUCC[{}]", order_uid, order_id, amount, actual_amount, source, pt, signature, sign, succ);
		return "OK";
	}
	
//	@RequestMapping(path = RequestPath.SINA_SHARE, produces = "application/json; charset=UTF-8")
//	@ResponseBody
//	public Object share(String token, String status, String rip) {
//		String res = HttpUtils.post(SinaApi.URL_SHARE, new String[] {
//				"access_token", token,
//				"status", status,
//				"rip", StringUtils.isEmpty(rip) ? "" : rip
//		});
//		return res;
//	}
	
}
